package com.fwmagic.flink.tablesql.stream;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.types.Row;
import org.apache.flink.util.Collector;

public class StreamTableWordCount {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        StreamTableEnvironment streamTableEnv = StreamTableEnvironment.create(env);

        DataStreamSource<String> lines = env.socketTextStream("localhost", 8888);

        SingleOutputStreamOperator<String> wordsDataStream = lines.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String line, Collector<String> out) throws Exception {
                String[] words = line.split("\\s");
                for (String word : words) {
                    out.collect(word);
                }
            }
        });

        Table table = streamTableEnv.fromDataStream(wordsDataStream, "word");

        Table result = table.groupBy("word")//分组
                .select("word,count(1) as counts");//聚合

        DataStream<Tuple2<Boolean, Row>> dataStream = streamTableEnv.toRetractStream(result, Row.class);

        dataStream.print();

        env.execute("StreamTableWordCount");

    }
}
